package com.buding.fx.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mingdongwei-jwk
 * @date 2022/12/08 15:13
 * @class com.buding.fx.netty
 * @Description
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("recevi msg: "+s);
        //获取到当前channel
        Channel channel = channelHandlerContext.channel();
        //这时我们遍历channelGroup，根据不同的情况，回送不同的消息
        channelGroup.forEach(ch -> {
            if(channel != ch){ //不是当前的channel，转发消息
                ch.writeAndFlush("[ 客户端 ]"+channel.remoteAddress()+"发送了消息："+s+"\n");
            }else{ //回显自己发送的消息给自己
                ch.writeAndFlush("[自己]发送了消息："+s);
            }
        });


    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户加入聊天的信息推送给其他在线的客户端
        //该方法会将channelGroup中所有的channel遍历，并发送消息
        channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "上线了" + sdf.format(new Date()) + "\n");
        //将当前channel加入到channelGroup
        channelGroup.add(channel);
        System.out.println(ctx.channel().remoteAddress()+"上线了"+"\n");

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //将该客户离开信息推送给“当前在线的用户”
        channelGroup.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "下线了" + "\n");
        System.out.println(ctx.channel().remoteAddress()+"下线了"+"\n");
        System.out.println("channelGroup size="+channelGroup.size());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        //关闭通道
        ctx.close();
    }
}
